extends CharacterBody3D

const MC_DELTA: float = 1.0 / 20.0

const GROUND_ACCEL_BASE_MULT = 0.55
const AIR_ACCEL_BASE_MULT = 0.05
const MOMENTUM_BASE_MULT = 0.91
const MOVE_MULT = 1
const GRAVITY = 0.6
const AIR_DRAG_MULT = 0.98

@export var jump_vel: float = 15
@export var stop_speed: float = 0.003

var look_sensitivity = ProjectSettings.get_setting("player/look_sensitivity")
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

var surface_slipperyness = 0.6

var vel_y = 0
var was_on_floor = false

@onready var camera: Camera3D = $Camera3D

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
	pass
#	if global_position.y < -30.0:
#		print('fell off world, fixing position')
#		global_position = Vector3(1.0, 5.0, 1.0)

func _physics_process(delta):

	var phys_norm = MC_DELTA / delta

	# Apply momentum adjustment
#	var real_slip = surface_slipperyness if is_on_floor() else 1.0
#	var fric_mult = pow(MOMENTUM_BASE_MULT * real_slip, delta / MC_DELTA)
#	velocity.x *= fric_mult
#	velocity.z *= fric_mult

	#print("fric_mult ", fric_mult)

	# Vertical velocity and jumping.
#	if is_on_floor():
#		if Input.is_action_pressed("move_jump") and Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
#			print("jump")
#			vel_y = jump_vel / phys_norm
#		else:
#			vel_y = 0
#	else:
#		# Apply vertical movement math
#		vel_y = (vel_y - (GRAVITY * 1)) * pow(AIR_DRAG_MULT, phys_norm)

	#print("yvel ", vel_y)

	# Update velocity for player input.
#	if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
#		var input_vec = Input.get_vector("move_left", "move_right", "move_forward", "move_backward").normalized()

#		var ixz = input_vec.x * global_transform.basis.x + input_vec.y * global_transform.basis.z
#		var ixzn = ixz.normalized()
#		var base_mult = GROUND_ACCEL_BASE_MULT if is_on_floor() else AIR_ACCEL_BASE_MULT
#		var slip_mult = pow(0.6 / real_slip, 3 * phys_norm) if is_on_floor() else 1.0
#		velocity += ixzn * base_mult * slip_mult * MOVE_MULT * phys_norm

	# Apply movement
#	velocity.y = vel_y
#	was_on_floor = is_on_floor()
#	move_and_slide()

	# Mouse capture.
	if Input.is_action_just_pressed("change_mouse_input"):
		Input.mouse_mode = Input.MOUSE_MODE_CAPTURED if Input.mouse_mode == Input.MOUSE_MODE_VISIBLE else Input.MOUSE_MODE_VISIBLE

func _input(event):
	if event is InputEventMouseMotion and Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
		rotate_y(-event.relative.x * look_sensitivity)
		camera.rotate_x(-event.relative.y * look_sensitivity)
		camera.rotation.x = clamp(camera.rotation.x, -PI/2, PI/2)
